<template>
  <div>
    <c-table-box ref="cTableBox" hide-func checkbox :other-filters="otherFilters" :table-config="tableConfig" @selection-change="selectionChange">
      <template #btn>
        <c-permission v-if="type==='all'" code="all">
          <!-- <c-button type="primary" opt-code="import">导入</c-button>
          <c-button type="primary" opt-code="export">导出</c-button> -->
          <c-button type="primary" opt-code="import" @click="importVisible=true">导入</c-button>
          <c-button type="primary" opt-code="export" @click="exportVisible=true">导出</c-button>
          <DrawingEdit :sel-data="selections" opt-code="editDrawing" @on-success="refreshTableData" />
          <c-button type="primary" opt-code="drawingComplate" @click="handleDrawingFinish">图纸完成</c-button>

        </c-permission>
        <c-permission v-else-if="type==='designing'" code="designing">
          <Split :sel-data="selections" opt-code="unlink" @on-success="refreshTableData" />
          <Abnormal :sel-data="selections" opt-code="submitException" @on-success="refreshTableData" />
          <c-button type="primary" opt-code="drawingMaintenance" @click="toMaintain('图纸维护', 'maintain')">图纸维护</c-button>
        </c-permission>
        <c-permission v-else-if="type==='wait'" code="giveOut">
          <c-button type="primary" opt-code="updateDrawing" @click="toMaintain('更新图纸')">更新图纸</c-button>
          <c-button type="primary" opt-code="giveOut" @click="drawIssue">图纸下发</c-button>
        </c-permission>
        <c-permission v-else-if="type==='pause'" code="pause">
          <c-button type="primary" opt-code="renew" @click="drawRecover">恢复图纸</c-button>
          <DesignLog :sel-data="selections" opt-code="designLog" @on-success="refreshTableData" />
        </c-permission>
      </template>
    </c-table-box>
    <import-files
      v-if="importVisible"
      title="导入"
      :visible.sync="importVisible"
      :config="fileImportConfig"
      @success="handleImportSuccess"
    />
    <export-files
      v-if="exportVisible"
      title="导出"
      :config="exportConfig"
      :visible.sync="exportVisible"
      @success="handleExportSuccess"
    />
  </div>
</template>
<script>
import { otherFiltersItem } from '@/utils'
import Split from './Split'
import Abnormal from './Abnormal'
import DesignLog from './DesignLog'
import DrawingEdit from './DrawingEdit'
import { drawingIssuance, postDrawingRecover, finishDrawing } from '@/api/shopDrawing'
export default {
  name: 'List',
  components: {
    Split,
    Abnormal,
    DesignLog,
    DrawingEdit
  },
  props: {
    type: {
      type: String,
      default: ''
    },
    activeType: {
      type: String,
      default: ''
    },
    serachFilters: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      importVisible: false,
      exportVisible: false,
      showEditDlg: false,
      tableConfig: {
        interfacePath: '/slm-admin/api/v1/shopDesignPicture/getPicture/page',
        hideFuncBar: true,
        sort: 'createTime',
        apiHeader: {
          'Permission-App': 'slm'
        },
        sortersRow: [
          { 'id': 'constCode', 'property': 'constCode', 'direction': 'DESC' }
        ],
        setting: [
          {
            prop: 'picTaskCode',
            label: '图纸任务编码',
            minWidth: 140,
            className: 'btn-green',
            isButton: true,
            clickFun: this.toDetail
          },
          {
            prop: 'drawingIssuanceNum',
            label: '图纸下发次数',
            minWidth: 120
          },
          {
            prop: 'constState',
            label: '门店建设状态',
            minWidth: 100,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'CONST_STATE'
            }
          },
          {
            prop: 'picTaskName',
            label: '图纸任务名称',
            minWidth: 120
          },
          {
            prop: 'picType',
            label: '图纸类型',
            minWidth: 100,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'PIC_TYPE'
            }
          },
          {
            prop: 'isRedesign',
            label: '是否重复设计',
            minWidth: 120,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            }
          },
          {
            prop: 'designRange',
            label: '设计范围',
            minWidth: 120,
            render: (h, row) => {
              return h('c-dict-range-view', {
                props: {
                  dictTypeCode: 'DECORATION_RANGE',
                  value: row.designRange
                }
              })
            }
          },
          {
            prop: 'decorationType',
            label: '装修形式',
            minWidth: 120,
            render: (h, row) => {
              return h('c-dict-range-view', {
                props: {
                  dictTypeCode: 'DECORATION_FORM',
                  value: row.decorationType
                }
              })
            }
          },
          {
            prop: 'designSpace',
            label: '设计区域',
            minWidth: 120,
            render: (h, row) => {
              return h('c-design-area', { props: { value: row.designSpace }})
            }
          },
          {
            prop: 'designBizType',
            label: '设计业务类型',
            minWidth: 120,
            render: (h, row) => {
              return h('c-dict-range-view', {
                props: {
                  dictTypeCode: 'BIZ_TYPE',
                  value: row.designBizType
                }
              })
            }
          },
          {
            prop: 'picTotalArea',
            label: '设计总面积',
            minWidth: 120
          },
          {
            prop: 'softwareSumArea',
            label: '软体区总面积',
            minWidth: '120'
          },
          {
            prop: 'suiteSumArea',
            label: '套房区总面积',
            minWidth: '120'
          },
          {
            prop: 'haveEAndC',
            label: '是否含成融定',
            minWidth: 120,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            }
          },
          {
            prop: 'eandCArea',
            label: '成融定面积',
            minWidth: 120
          },
          {
            prop: 'newBusinessAreaSummary',
            label: '新业务面积汇总',
            minWidth: 140
          },
          {
            prop: 'expectEndTime',
            label: '预计设计完成时间',
            minWidth: 140,
            formatData: this.$parseTimeYMD('expectEndTime')
          },
          {
            prop: 'isDesignOverdue',
            label: '图纸设计是否超时',
            minWidth: 140,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            }
          },
          {
            prop: 'overdueDay',
            label: '超期时长',
            minWidth: 100
          },
          {
            prop: 'designUnitName',
            label: '设计单位',
            minWidth: 120
          },
          {
            prop: 'designerName',
            label: '设计师',
            minWidth: 100
          },
          {
            prop: 'schedule',
            label: '图纸进度',
            minWidth: 100,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'PIC_DESIGN_SCHEDULE'
            }
          },
          {
            prop: 'state',
            label: '图纸状态',
            minWidth: 100,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'PIC_DESIGN_STATE'
            }
          },
          {
            prop: 'maintainTimes',
            label: '图纸维护次数',
            minWidth: 140
          },
          {
            prop: 'constCode',
            label: '门店建设项目号',
            minWidth: 140
          },
          {
            prop: 'shopName',
            label: '所属门店',
            minWidth: 120
          },
          {
            prop: 'clientName',
            label: '所属客户',
            minWidth: 100
          },
          {
            prop: 'officeName',
            label: '所属办事处',
            minWidth: 120
          },
          {
            prop: 'isKaMarket',
            label: '是否KA卖场',
            minWidth: 120,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            }
          },
          {
            prop: 'picUrgentLevel',
            label: '图纸紧急程度',
            minWidth: 130,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'PIC_URGENT_LEVEL'
            }
          },
          {
            prop: 'shopLevelCode',
            label: '店面等级',
            minWidth: 100,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'SHOP_LEVEL_CODE'
            }
          },
          {
            prop: 'designLog',
            label: '图纸设计日志',
            minWidth: 130
          },
          {
            prop: 'createTime',
            label: '图纸创建时间',
            minWidth: 130
          }
        ]
      },
      typeFilters: [],
      selections: []
    }
  },
  computed: {
    otherFilters() {
      return [...this.serachFilters, ...this.typeFilters]
    },
    exportConfig() {
      return [{
        code: 'export',
        name: '图纸管理',
        dataApi: '/slm-admin/api/v1/shopDesignPicture/export',
        selectedRows: this.selections,
        paramsRaw: {},
        filtersRaw: this.otherFilters,
        queryField: 'id',
        headers: {
          // 'Permission-Code': 'drawingsmanagement',
          'Permission-App': 'slm'
        }
      }]
    },
    fileImportConfig() {
      return [{
        code: 'import',
        name: '图纸管理',
        apiUrl: '/slm-admin/api/v1/shopDesignPicture/importExcel',
        selectedRows: this.selections,
        paramsRaw: {},
        filtersRaw: this.otherFilters
      }]
    }
  },
  watch: {
    type: {
      handler(v) {
        this.setOtherFilters(v)
      },
      immediate: true
    },
    serachFilters: {
      handler(v) {
        if (this.activeType !== this.type) return
        this.$nextTick(() => {
          this.$refs.cTableBox.initTableData()
        })
      }
    }
  },
  activated() {
    if (this.ready && this.refreshTableData) {
      this.refreshTableData()
    }
  },
  deactivated() {
    this.ready = true
  },
  methods: {
    // 设置过滤条件
    setOtherFilters(v) {
      switch (v) {
        case 'all':
          this.typeFilters = [
            otherFiltersItem('enable', '1', '=')
          ]
          break
        case 'designing':
          this.typeFilters = [
            otherFiltersItem('schedule', 'A', '='),
            otherFiltersItem('enable', '1', '='),
            otherFiltersItem('state', 'NORMAL', '='),
            otherFiltersItem('isEnd', '0', '=')
          ]
          break
        case 'wait':
          this.typeFilters = [
            otherFiltersItem('schedule', 'C', '='),
            otherFiltersItem('enable', '1', '='),
            otherFiltersItem('state', 'NORMAL', '='),
            otherFiltersItem('isEnd', '0', '=')
          ]
          break
        case 'pause':
          this.typeFilters = [
            otherFiltersItem('state', '[APPLY,ABNORMAL]', 'in'),
            otherFiltersItem('enable', '1', '='),
            otherFiltersItem('isEnd', '0', '=')
          ]
          break
      }
    },
    selectionChange(v) {
      this.selections = v
    },
    refreshTableData(v = 'onPage') {
      this.$nextTick(() => {
        this.$refs.cTableBox.initTableData(v)
      })
    },
    // 图纸维护
    toMaintain(warnText = '图纸维护', type) {
      if (!this.singleJudge(this.selections, warnText, true)) {
        return
      }
      if (type === 'maintain' && this.selections[0].state !== 'NORMAL') {
        this.$message.warning('【正常】数据才能进行图纸维护！')
        return
      }
      const d = this.selections[0] || {}
      this.$router.push({ name: 'ShopDrawingMaintain', query: { id: d.id, picTaskCode: d.picTaskCode }})
    },
    // 图纸下发
    drawIssue() {
      if (!this.singleJudge(this.selections, '图纸下发', true)) {
        return
      }
      if (this.selections.filter(e => e.picType === 'SG').length > 10) {
        this.$message.warning('施工图下发一次勾选数量请不要超过10条')
        return
      }
      const ids = this.selections.map(e => e.id)
      return drawingIssuance(ids).then(res => {
        this.$message.success('图纸下发成功！')
        this.refreshTableData()
      })
    },
    // 恢复图纸
    drawRecover() {
      if (!this.singleJudge(this.selections, '恢复图纸', true)) {
        return
      }
      if (this.selections.some(e => e.state !== 'ABNORMAL')) {
        this.$message.warning('只能恢复异常暂停的图纸！')
        return
      }
      return this.$msgbox({
        title: '提示',
        message: `<div style="width:100%;word-break: break-all;white-space: pre-wrap;">所选图纸 ${this.selections.map(e => e.picTaskCode).join(',')} 将恢复设计是否确认？</div>`,
        showCancelButton: true,
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }).then(() => {
        // 可批量操作，仅图纸状态值为“异常暂停”的，允许此操作，点击此按钮后，记录恢复时间，
        // 同时重新记录预计设计完成时间：恢复时间-暂停时间+原预计完成时间
        return this.$gsec('EXCEPT009').then(([cfg, ecd]) => {
          const d = this.selections[0]
          ecd.constCode = d.constCode
          ecd.bizCode = d.picTaskCode
          ecd.bizName = d.picTaskName
          ecd.modelId = d.id
          ecd.exceptionDesc = '恢复图纸'
          ecd.bpmInstanceNo = cfg.bpmInstanceNo || ''
          const t = this.$gsed()
          t.exceptionDesc = '恢复图纸'
          t.remark = ''
          ecd.shopExceptionDetailDTOS = [t]
          return postDrawingRecover(ecd).then(res => {
            this.$message.success('恢复图纸成功！')
            this.refreshTableData()
          })
        })
      })
    },
    handleDrawingFinish() {
      if (!this.singleJudge(this.selections, '图纸完成', true)) {
        return
      }
      if (this.selections[0].picType !== 'SG' || this.selections[0].schedule !== 'F') {
        this.$message.warning('图纸类型为施工图，图纸进度为已完成才能进行此操作')
        return
      }
      const data = {
        constCode: this.selections[0].constCode,
        isEndAllDesign: this.selections[0].designRange === 'DOOR' ? 1 : (this.selections[0].designRange === 'STORES' ? 2 : undefined),
        picTaskCode: this.selections[0].picTaskCode
      }
      finishDrawing(data).then(res => {
        if (res.success) {
          this.$message.success('操作成功')
          this.refreshTableData()
        }
      })
    },
    // 详情
    toDetail(row) {
      let type = 'bc'
      if (row.picType === 'SG' && row.designRange === 'DOOR') {
        type = 'door'
      } else if (row.picType === 'SG' && row.designRange === 'STORES') {
        type = 'stores'
      }
      this.$router.push({ name: 'ShopDrawingDetail', query: { id: row.id, picTaskCode: row.picTaskCode, designRange: row.designRange, type, picType: row.picType }})
    },
    // 导出成功
    handleExportSuccess() {
      this.$message.success('导出成功！')
    },
    // 导入成功
    handleImportSuccess() {
      this.$message.success('导入成功！')
    }
  }
}
</script>
